package com.mc.developmentkit.pay;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import com.alipay.sdk.app.PayTask;
import com.mc.developmentkit.bean.GetPaidInfo;
import com.mc.developmentkit.bean.WFTPayInfo;
import com.mc.developmentkit.bean.WXPayInfo;
import com.mc.developmentkit.bean.ZFBPayInfo;
import com.mc.developmentkit.callback.AliPayListener;
import com.mc.developmentkit.https.HttpUtils;
import com.mc.developmentkit.config.MCConstant;
import com.mc.developmentkit.json.Json;
import com.mc.developmentkit.utils.ToastUtil;
import com.switfpass.pay.MainApplication;
import com.switfpass.pay.activity.PayPlugin;
import com.switfpass.pay.activity.PayResult;
import com.switfpass.pay.bean.RequestMsg;
import com.tencent.mm.sdk.modelpay.PayReq;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;

import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by LeBron on 2016/12/20.
 */

public class MCThirdPartyPay {


    private static MCThirdPartyPay instance;
    private ZFBPayInfo zfbPayInfo;
    private Map<String, Object> map;
    private String json;
    private String json1;
    private String msg1;
    private String appid;

    private MCThirdPartyPay() {
    }

    public static MCThirdPartyPay getInstance() {
        if (null == instance) {
            instance = new MCThirdPartyPay();
        }
        return instance;
    }

    private Activity activity;

    public void wftPay(Activity activity, String url, GetPaidInfo getPaidInfo) {
        this.activity = activity;
        HttpUtils.POST(tHandler, url, goodsInfo(getPaidInfo), false);
    }


    public void wxPay(Activity activity, String url, GetPaidInfo getPaidInfo) {
        this.activity = activity;
        HttpUtils.POST(xHandler, url, goodsInfo(getPaidInfo), false);
    }

    public void wx2wftPay(Activity activity, String url, GetPaidInfo getPaidInfo,String id) {
        this.activity = activity;
        appid = id;
        HttpUtils.POST(vHandler, url, goodsInfo(getPaidInfo), false);
    }

    public void aliPay(final Activity activity, String url, GetPaidInfo getPaidInfo,  AliPayListener aliPayListener) {
        this.aliPayListener = aliPayListener;
        this.activity = activity;
        HttpUtils.POST(zHandler, url, goodsInfo(getPaidInfo), false);
    }


    /**
     * 微信和微付通Handler
     */
    Handler vHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                   Log.e("威富通和微信json",msg.obj.toString());
                    try {
                        JSONObject jsonObject = new JSONObject(msg.obj.toString());
                        int status = jsonObject.getInt("status");
                        String msg2 = jsonObject.getString("msg");
                        if(status==1){
                            String wxtype = jsonObject.getString("wxtype");
                            if(wxtype.equals("wft")){
                                RequestMsg requestMsg = new RequestMsg();
                                requestMsg.setTokenId(jsonObject.getString("token_id"));
                                requestMsg.setAppId(appid);
                                requestMsg.setSubOpenID(jsonObject.getString("sub_appid"));
                                requestMsg.setTradeType(MainApplication.WX_APP_TYPE);
                                PayPlugin.unifiedAppPay(activity, requestMsg);
                            }else{
                                IWXAPI api = WXAPIFactory.createWXAPI(activity, null);
                                api.registerApp(jsonObject.getString("appid"));
                                PayReq request = new PayReq();
                                request.appId = jsonObject.getString("appid");
                                request.partnerId = jsonObject.getString("partnerid");
                                request.prepayId = jsonObject.getString("prepayid");
                                request.nonceStr = jsonObject.getString("noncestr");
                                request.timeStamp = jsonObject.getString("timestamp");
                                request.packageValue = jsonObject.getString("package");
                                request.sign = jsonObject.getString("sign");
                                api.sendReq(request);
                            }
                        }else{
                            ToastUtil.showToast(msg2);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                        Log.e("解析威富通和微信异常",e.toString());
                    }
                    break;
                case 2:
                    ToastUtil.showToast("网络异常");
                    break;
            }
        }
    };


    /**
     * 微付通Handler
     */
    Handler tHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    WFTPayInfo wftPayInfo = Json.DNSWFTPay(msg.obj.toString());
                    if (wftPayInfo != null) {
                        RequestMsg requestMsg = new RequestMsg();
                        requestMsg.setTokenId(wftPayInfo.tokenId);
                        requestMsg.setAppId(MCConstant.getWxAppId());
                        requestMsg.setTradeType(MainApplication.WX_APP_TYPE);
                        PayPlugin.unifiedAppPay(activity, requestMsg);
                    } else {
                        ToastUtil.showToast("微付通订单信息为空");
                    }
                    break;
                case 2:
                    ToastUtil.showToast("网络异常");
                    break;
            }
        }
    };

    /**
     * 微信Handler
     */
    Handler xHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    WXPayInfo wxPayInfo = Json.DNSWXPay(msg.obj.toString());
                    if (wxPayInfo != null) {
                        IWXAPI api = WXAPIFactory.createWXAPI(activity, null);
                        api.registerApp(wxPayInfo.appid);
                        PayReq request = new PayReq();
                        request.appId = wxPayInfo.appid;
                        request.partnerId = wxPayInfo.partnerid;
                        request.prepayId = wxPayInfo.prepayid;
                        request.nonceStr = wxPayInfo.noncestr;
                        request.timeStamp = wxPayInfo.timestamp;
                        request.packageValue = wxPayInfo.packagvalues;
                        request.sign = wxPayInfo.sign;
                        api.sendReq(request);
                    } else {
                        return;
                    }
                    break;
                case 2:
                    ToastUtil.showToast("网络异常！");
                    break;
            }
        }
    };

    /**
     * 支付宝Handler
     */
    Handler zHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    zfbPayInfo = Json.DNSZFBPay(activity,msg.obj.toString());
                    map = new HashMap<String, Object>();
                    Log.e("zfbPayInfo.orderInfo", zfbPayInfo.orderInfo+"---");
                    Runnable payRunnable = new Runnable() {
                        @Override
                        public void run() {
                            PayTask alipay = new PayTask(activity);
                            String result = alipay.pay(zfbPayInfo.orderInfo, true);
                            Message msg = new Message();
                            msg.what = 1;
                            msg.obj = result;
                            mHandler.sendMessage(msg);
                        }
                    };
                    Thread payThread = new Thread(payRunnable);
                    payThread.start();
                    break;
                case 2:
                    ToastUtil.showToast("网络异常");
                    break;
            }
        }
    };

    private AliPayListener aliPayListener;

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1: {
                    PayResult payResult = new PayResult((String) msg.obj);
                    /**
                     * 同步返回的结果必须放置到服务端进行验证（验证的规则请看https://doc.open.alipay.com/doc2/
                     * detail.htm?spm=0.0.0.0.xdvAU6&treeId=59&articleId=103665&
                     * docType=1) 建议商户依赖异步通知
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为“9000”则代表支付成功，具体状态码代表含义可参考接口文档
                    Log.e("支付返回码：", resultStatus+"---");
                    if (TextUtils.equals(resultStatus, "9000")) {
                        msg1 = "支付成功";
                        json1 = "{\"msg\":\"" + msg1 + "\",\"code\":" + resultStatus+ "}";
                    } else {
                        // 判断resultStatus 为非"9000"则代表可能支付失败
                        // "8000"代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，最终交易是否成功以服务端异步通知为准（小概率状态）
                        if (TextUtils.equals(resultStatus, "8000")) {
                            msg1 = "等待支付结果";
                            json1 = "{\"msg\":\"" + msg1 + "\",\"code\":\"" + resultStatus + "\"}";
                        } else {
                            if (TextUtils.equals(resultStatus, "4001")) {
                                msg1 = "支付成功";
                                json1 = "{\"msg\":\"" + msg1 + "\",\"code\":\"" + resultStatus + "\"}";
                            } else {
                                // 其他值就可以判断为支付失败，包括用户主动取消支付，或者系统返回的错误
                                msg1 = "支付失败";
                                json1 = "{\"msg\":\""  + msg1 + "\",\"code\":" + resultStatus+ "}";
                            }
                        }
                    }
                    if(aliPayListener==null){
                        ToastUtil.showToast(msg1);
                    }else{
                        aliPayListener.zfbPayResult(json1);
                    }
                    break;
                }
                default:
                    break;
            }
        }
    };


    public HashMap<String, String> goodsInfo(GetPaidInfo getPaidInfo) {
        HashMap<String, String> map = new HashMap<>();
        try {
            if (!(getPaidInfo.good_name == null || getPaidInfo.good_name.isEmpty())) {
                map.put("good_name", getPaidInfo.good_name);
            }
            if (!(getPaidInfo.good_id == null || getPaidInfo.good_id.isEmpty())) {
                map.put("good_id", getPaidInfo.good_id);
            }
            if (!(getPaidInfo.good_price == null || getPaidInfo.good_price.isEmpty())) {
                map.put("price", getPaidInfo.good_price);
            }
            if (!(getPaidInfo.userId == null || getPaidInfo.userId.isEmpty())) {
                map.put("user_id", getPaidInfo.userId);
            }
            if (!(getPaidInfo.user_name == null || getPaidInfo.user_name.isEmpty())) {
                map.put("user_name", getPaidInfo.user_name);
            }
            if (!(getPaidInfo.user_sign == null || getPaidInfo.user_sign.isEmpty())) {
                map.put("token", getPaidInfo.user_sign);
            }
            if (!(getPaidInfo.payType == null || getPaidInfo.payType.isEmpty())) {
                map.put("pay_way", getPaidInfo.payType);
            }
            if (!(getPaidInfo.body == null || getPaidInfo.body.isEmpty())) {
                map.put("body", getPaidInfo.body);
            }
            if (!(getPaidInfo.code == null || getPaidInfo.code.isEmpty())) {
                map.put("code", getPaidInfo.code);
            }
            if (!(getPaidInfo.good_title == null || getPaidInfo.good_title.isEmpty())) {
                map.put("title", getPaidInfo.good_title);
            }
            if (!(getPaidInfo.packageId == null || getPaidInfo.packageId.isEmpty())) {
                map.put("package_id", getPaidInfo.packageId);
            }
            if (!(getPaidInfo.extend == null || getPaidInfo.extend.isEmpty())) {
                map.put("extend", getPaidInfo.extend);
            }
            if (!(getPaidInfo.promote_id == null || getPaidInfo.promote_id.isEmpty())) {
                map.put("promote_id", getPaidInfo.promote_id);
            }
            if (!(getPaidInfo.pay_amount == null || getPaidInfo.pay_amount.isEmpty())) {
                map.put("pay_amount", getPaidInfo.pay_amount);
            }
            if (!(getPaidInfo.account == null || getPaidInfo.account.isEmpty())) {
                map.put("account", getPaidInfo.account);
            }
            if (!(getPaidInfo.real_pay_amount == null || getPaidInfo.real_pay_amount.isEmpty())) {
                map.put("real_pay_amount", getPaidInfo.real_pay_amount);
            }
            JSONObject jsonObject = new JSONObject();
            if(getPaidInfo.good_type ==1){
                jsonObject.put("type","1");
            }
            if(getPaidInfo.good_type ==2){
                jsonObject.put("type","2");
            }
            if (!(getPaidInfo.game_id == null || getPaidInfo.game_id.isEmpty())) {
                jsonObject.put("game_id", getPaidInfo.game_id);
            }
            map.put("good_info", jsonObject.toString());
        } catch (Exception e) {
            e.printStackTrace();
            Log.e("获取订单信息异常异常", e.toString());
        }
Log.e("商品请求信息",map.toString());
        return map;
    }
}
